import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const env = __wxConfig.envVersion
let userInfo = null
let token = ''

try {
  userInfo = userInfo || uni.getStorageSync(`${env}_userInfo`)
  token = token || uni.getStorageSync(`${env}_token`)
} catch (error) {
  console.log('userInfo|token|deviceObj-error:', error)
}

const store = new Vuex.Store({
  state: {
    token,
    userInfo,
  },
  actions: {
    setToken({ commit }, token) {
      commit('setToken', token)
    },
    setUserInfo({ commit }, userInfo) {
      commit('setUserInfo', userInfo)
    },
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      uni.setStorageSync(`${env}_token`, token)
      console.log('store.state.token has changed:', token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
      uni.setStorageSync(`${env}_userInfo`, userInfo)
      console.log('store.state.userInfo has changed:', userInfo)
    },
  }
})

export default store
